import React, { useState } from 'react';
import { Card, Radio, message, Spin, Result, Button } from 'antd';
import { pdfApi } from '../../services/api';
import { handleApiError, downloadFile } from '../../utils/error';
import FileUploader from '../common/FileUploader';

const PDFConverter: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [convertType, setConvertType] = useState<'word' | 'ppt'>('word');
  const [error, setError] = useState<string | null>(null);

  const handleUpload = async (files: File[]) => {
    const file = files[0];
    setError(null);
    try {
      setLoading(true);
      let response: Blob;
      
      if (convertType === 'word') {
        response = await pdfApi.convertToWord(file);
        downloadFile(response, 'converted.docx');
      } else {
        response = await pdfApi.convertToPPT(file);
        downloadFile(response, 'converted.pptx');
      }
      
      message.success('转换成功！');
    } catch (err) {
      handleApiError(err);
      setError('转换失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setError(null);
  };

  return (
    <Card
      title="PDF转换"
      extra={
        <Radio.Group
          value={convertType}
          onChange={(e) => setConvertType(e.target.value)}
          disabled={loading}
        >
          <Radio.Button value="word">转Word</Radio.Button>
          <Radio.Button value="ppt">转PPT</Radio.Button>
        </Radio.Group>
      }
    >
      {error ? (
        <Result
          status="error"
          title={error}
          extra={
            <Button type="primary" onClick={handleReset}>
              重试
            </Button>
          }
        />
      ) : (
        <>
          <FileUploader
            accept=".pdf"
            onUpload={handleUpload}
            loading={loading}
            description={`将PDF转换为${convertType === 'word' ? 'Word文档' : 'PPT演示文稿'}`}
          />

          {loading && (
            <div style={{ textAlign: 'center', margin: '24px 0' }}>
              <Spin tip="正在转换中..." />
            </div>
          )}
        </>
      )}
    </Card>
  );
};

export default PDFConverter; 